<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Db;


/**
 * 合同的业务类型
 * Class BusinessType
 * @package app\admin\controller
 */
class ContractType extends AdminBase
{
    private $contract_type_model;

    public function _initialize()
    {
        parent::_initialize();
        $this->contract_type_model = model('ContractType');

    }

    public function index()
    {
        $list = [];
        $top_type_list = $this->contract_type_model->getAllTypeByPid(0);
        foreach ($top_type_list as $v) {
            $list[] = $v;
            $list = array_merge($list, $this->contract_type_model->getAllTypeByPid($v['id']));
        }

        return $this->fetch('index', [
            'type_list' => $list
        ]);
    }

    /**
     * 添加业务类型
     * @return mixed|string
     */
    public function add()
    {
        //获取所有的一级分类
        $top_type_list = $this->contract_type_model->getAllTopType();

        $parent_id_slecet = $this->request->param('pid', 0, 'intval');

        if ($this->request->isAjax()) {
            $type = $this->request->param('type', '', 'app\common\controller\ParamFilter::normalParam');
            if (mb_strlen($type) > 50) {
                return ajax_return_error('类型名字长度超出限制，最多50个字！');
            }

            $parent_id = $this->request->param('parent_id', 0, 'intval');
            if ($parent_id > 0) {
                $parent_type_info = $this->contract_type_model->getInfo(['id' => $parent_id]);
                if (empty($parent_type_info)) {
                    return ajax_return_error('指定父级业务分类不存在，请检查！');
                }

                if ($parent_type_info['parent_id'] != 0) {
                    return ajax_return_error('抱歉，目前只支持两层分类！');
                }
            }

            $data = [
                'type' => $type,
                'parent_id' => $parent_id,
            ];

            //检查是否存在同名分类
            $same_type_info = $this->contract_type_model->getInfo([
                'type' => $type,
                'parent_id' => $parent_id,
            ]);
            if (!empty($same_type_info)) {
                return ajax_return_error('指定分类下已存在同名分类！');
            }

            if ($this->contract_type_model->addData($data)) {
                return ajax_return_adv('添加成功！');
            } else {
                return ajax_return_error('添加失败！');
            }
        }

        return $this->fetch('add', [
            'top_type_list' => $top_type_list,
            'parent_id_slecet' => $parent_id_slecet,
        ]);
    }

    public function edit()
    {
        //获取所有的一级分类
        $top_type_list = $this->contract_type_model->getAllTopType();

        $id = $this->request->param('id', 0, 'intval');
        $old_info = $this->contract_type_model->getInfo(['id' => $id]);

        if ($this->request->isAjax() && $id > 0) {
            $type = $this->request->param('type', '', 'app\common\controller\ParamFilter::normalParam');
            if (mb_strlen($type) > 50) {
                return ajax_return_error('类型名字长度超出限制，最多50个字！');
            }
            $parent_id = $this->request->param('parent_id', 0, 'intval');
            if ($parent_id > 0) {
                $parent_type_info = $this->contract_type_model->getInfo(['id' => $parent_id]);
                if (empty($parent_type_info)) {
                    return ajax_return_error('指定父级业务分类不存在，请检查！');
                }

                if ($parent_type_info['parent_id'] != 0) {
                    return ajax_return_error('抱歉，目前只支持两层分类！');
                }
            }

            $data = [
                'type' => $type,
                'parent_id' => $parent_id,
            ];

            //检查是否存在同名分类
            if ($type != $old_info['type']) {
                $same_type_info = $this->contract_type_model->getInfo([
                    'type' => $type,
                    'parent_id' => $parent_id,
                ]);
                if (!empty($same_type_info) && $same_type_info['id'] != $id) {
                    return ajax_return_error('指定分类下已存在同名分类！');
                }
            }


            if ($this->contract_type_model->saveDate($id, $data)) {
                return ajax_return_adv('修改成功！');
            } else {
                return ajax_return_error('修改失败！');
            }
        }

        return $this->fetch('edit', [
            'top_type_list' => $top_type_list,
            'type_info' => $old_info,
            'id' => $id,
        ]);
    }

    /**
     * 删除菜单
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        $sub_type = $this->contract_type_model->where(['parent_id' => $id])->find();
        if (!empty($sub_type)) {
            return ajax_return_error('请先删除所有子分类！');
        }
        if ($this->contract_type_model->destroy($id)) {
            return ajax_return_adv('删除成功');
        } else {
            return ajax_return_error('删除失败');
        }
    }
    /**
     * 删除菜单
     */
    public function deleteAll()
    {
        $ids = $this->request->param('ids', '', 'trim');
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter(array_map(function($v){
            return (int)$v;
        }, $ids)));

        $flag = true;
        $err_msg = '';
        Db::startTrans();
        foreach ($ids as $id) {
            $sub_type = $this->contract_type_model->field('id')->where(['parent_id' => $id])->find();
            if (!empty($sub_type)) {
                $title = $this->contract_type_model->field('type')->where(['id' => $id])->find();
                $err_msg = '分类（'.$title['type'].'）下存在子分类，不可删除';
                $flag = false;
                break;
            }

            if (!$this->contract_type_model->destroy($id)) {
                $err_msg = '删除失败,请重试!';
                $flag = false;
                break;
            }
        }

        if ($flag) {
            Db::commit();
            return ajax_return_adv('删除成功');
        } else {
            Db::rollback();
            return ajax_return_error($err_msg);
        }

    }
}
